import { WithId, ObjectId } from 'mongodb'
import * as db from '../db'
import { IRecruit, IFindRecruit } from '../types'
import { recruitCollection } from '../db'
import { stats } from '../stats'
import { tokens } from './user.service'

// 根据关键词查询详细信息
export async function find(
  recruit: IFindRecruit = {}
): Promise<WithId<IRecruit>[]> {
  let sql = {}
  if (recruit.salary !== undefined && recruit.salary !== '不限') {
    const min = Number(recruit.salary.split('-')[0])
    const max = Number(recruit.salary.split('-')[1].split('K')[0])
    const str = {
      'salary.min': { $gte: min },
      'salary.max': { $lte: max }
    }
    sql = Object.assign(sql, str)
  }

  if (recruit.keyWords !== undefined) {
    const strArr = []
    for (let i = 0; i < recruit.keyWords.length; i++) {
      for (let j = i; j < recruit.keyWords.length; j++) {
        const str = recruit.keyWords.substring(i, j + 1)
        strArr.push(str)
      }
    }
    let objS = {}
    const objectSname = []
    const objectSkey = []
    for (let i = 0; i < strArr.length / 2; i++) {
      if (strArr[i].length === 2 || strArr[i].length === 3) {
        objS = {
          positionName: { $regex: strArr[i], $options: 'i' }
        }
        objectSname.push(objS)
        objS = {
          keyWords: { $regex: strArr[i], $options: 'i' }
        }
        objectSkey.push(objS)
      }
    }
    const res = await db.companyCollection
      .find({
        companyShortName: { $regex: recruit.keyWords, $options: 'i' }
      })
      .toArray()
    let obj = {}
    let str = {}
    const object = []
    for (const item of res) {
      obj = {
        companyId: item._id
      }
      object.push(obj)
    }
    str = {
      $or: [
        { positionName: { $regex: recruit.keyWords, $options: 'i' } },
        { keyWords: { $regex: recruit.keyWords, $options: 'i' } },
        ...object,
        ...objectSname,
        ...objectSkey
      ]
    }
    sql = Object.assign(sql, str)
  }
  if (recruit.city !== undefined && recruit.city !== '全国') {
    const str = {
      city: recruit.city
    }
    sql = Object.assign(sql, str)
  }

  if (recruit.workYear !== undefined && recruit.workYear !== 1) {
    const str = {
      workYear: recruit.workYear
    }
    sql = Object.assign(sql, str)
  }
  if (recruit.education !== undefined) {
    const str = {
      education: recruit.education
    }
    sql = Object.assign(sql, str)
  }

  const res = await db.recruitCollection
    .aggregate([
      {
        $match: sql
      },
      {
        $lookup: {
          from: 'company',
          localField: 'companyId',
          foreignField: '_id',
          as: 'companys'
        }
      },
      {
        $lookup: {
          from: 'user',
          localField: 'interviewerId',
          foreignField: '_id',
          as: 'users'
        }
      }
    ])
    .toArray()
  if (recruit.companySize !== undefined) {
    const res2 = await db.companyCollection
      .find({
        companySize: recruit.companySize
      })
      .toArray()
    if (res2.length === 0) return []
    let flag = false
    for (let i = 0; i < res.length; i++) {
      for (let j = 0; j < res2.length; j++) {
        if (res[i].companyId.equals(res2[j]._id)) {
          flag = true
        }
      }
      if (!flag) res.splice(i, 1)
    }
  }
  if (recruit.financeStage !== undefined) {
    const res2 = await db.companyCollection
      .find({
        financeStage: recruit.financeStage
      })
      .toArray()
    if (res2.length === 0) return []
    let flag = false
    for (let i = 0; i < res.length; i++) {
      for (let j = 0; j < res2.length; j++) {
        if (res[i].companyId.equals(res2[j]._id)) {
          flag = true
        }
      }
      if (!flag) res.splice(i, 1)
    }
  }
  return res
}

// 根据公司id查询发布人信息
export async function companyRe(companyId: string) {
  const result = await db.recruitCollection
    .aggregate([
      {
        $match: { companyId: new ObjectId(companyId) }
      },
      {
        $lookup: {
          from: 'user',
          localField: 'interviewerId',
          foreignField: '_id',
          as: 'users'
        }
      }
    ])
    .toArray()
  return result
}

// 获取发布职位列表
export async function listRecs(interviewerId: string) {
  return recruitCollection
    .find({
      interviewerId: new ObjectId(interviewerId)
    })
    .toArray()
}

// 添加职位
export async function add(recruit: IRecruit, token: string) {
  const id = tokens.get(token)
  const user = await db.userCollection.findOne({
    _id: id
  })
  if (user.companyId === null) throw stats.ERR_NOT_FOUND
  const res = await recruitCollection.insertOne({
    companyId: user.companyId,
    interviewerId: user._id,
    ...recruit
  })
  return res.insertedId
}

// 编辑职位
export async function update(_id: string, recruit: IRecruit) {
  const count = await db.recruitCollection.findOne({
    _id: new ObjectId(_id)
  })
  if (count === undefined) throw stats.ERR_NOT_FOUND
  await db.recruitCollection.findOneAndUpdate(
    {
      _id: new ObjectId(_id)
    },
    {
      $set: recruit
    }
  )
}

// 删除职位
export async function remove(_id: string) {
  const result = await recruitCollection.findOneAndDelete({
    _id: new ObjectId(_id)
  })
  if (result === null) throw stats.ERR_NOT_FOUND
  return result.value
}

// 根据职位id查询职位信息
export async function findOne(_id: string) {
  const result = await db.recruitCollection.findOne({
    _id: new ObjectId(_id)
  })
  if (result === null) throw stats.ERR_NOT_FOUND
  return result
}

// 根据职位id查职位表，拿到公司id后在查公司表获取公司信息
export async function listRecruit(recruitId: string) {
  const recruit = await db.recruitCollection.findOne({
    _id: new ObjectId(recruitId)
  })
  if (recruit === null) throw stats.ERR_NOT_FOUND
  const companyInfo = await db.companyCollection.findOne({
    _id: recruit.companyId
  })
  return companyInfo
}

// 根据关键字查询职位信息
export async function findkey(record: IRecruit) {
  const result = await db.recruitCollection.findOne({
    keyWords: record.keyWords
  })
  if (result === null) throw stats.ERR_NOT_FOUND
  return result
}
